//
//  AFNetworkingTool.m
//  AFNetworkingTool
//
//  Created by 张国梁 on 15/11/4.
//  Copyright © 2015年 CoderGL. All rights reserved.
//

#import "AFNetworkingTool.h"

@implementation AFNetworkingTool  /** 内部封装afn 依赖弱 以后更换框架容易*/


+ (void)netWorkingStatusNotReachable:(void (^)())NotReachable ReachableViaWWAN:(void (^)())ReachableViaWWAN ReachableViaWiFi:(void (^)())ReachableViaWiFi {
    
    /** 网络状态
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 没有网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // WiFi
     */
    
    // 获取网络管理者单例
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 设置网络状态改变调用的代码
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                if (NotReachable) {
                    NotReachable();
                }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                if (ReachableViaWWAN) {
                    ReachableViaWWAN();
                }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                if (ReachableViaWiFi) {
                    ReachableViaWiFi();
                }
                break;
            default:
                break;
        }
    }];
    
    // 开始监听网络状态
    [manager startMonitoring];
}


+ (void)getWithUrl:(NSString *)url params:(id)params success:(void (^)(NSURLSessionDataTask * _Nullable, NSDictionary * _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nullable))failure {
    
    // 创建网络请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 发送网络请求
    [manager GET:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSError *error = nil;
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        NSAssert(error == nil, @"Json解析有错误");
        if (success) {
            success(task, responseDict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSAssert(error == nil, @"有错误");
        if (failure) {
            failure(task, error);
        }
    }];
    
}


+ (void)postWithUrl:(NSString *)url params:(id)params success:(void (^)(NSURLSessionDataTask * _Nullable, NSDictionary * _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nullable))failure {
    
    // 创建网络请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // 发送网络请求
    [manager GET:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSError *error = nil;
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        NSAssert(error, @"Json解析有错误");
        if (success) {
            success(task, responseDict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSAssert(error == nil, @"有错误");
        if (failure) {
            failure(task, error);
        }
    }];
    
}



#pragma mark - Session 下载下载文件
+ (void)downloadWithUrl:(NSString *)urlStr success:(void (^)(NSURL * _Nullable, NSURLResponse * _Nullable))success failure:(void (^)(NSURLResponse * _Nullable, NSURL * _Nullable, NSError * _Nullable))failure {
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    
    NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        // 指定下载文件保存的路径
        // NSLog(@"%@ %@", targetPath, response.suggestedFilename);
        
        // 将下载文件保存在缓存路径中
        NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        
        // 具体路径
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
        
        // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        //        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        if (success) {
            success(fileURL, response);
        }
        return fileURL;
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSAssert(error == nil, @"有错误");
        NSLog(@"%@ %@", filePath, error);
        if (failure) {
            failure(response, filePath, error);
        }
    }];
    
    // 开始下载
    [task resume];
}



+ (void)postUploadWithUrl:(NSString *)url params:(id)params fileData:(NSData *)fileData name:(NSString *)name mimeType:(NSString *)mimeTpye success:(void(^)( id responseObject))success failure:(void(^)(NSError *error))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 要上传保存在服务器中的名称
        // 使用时间来作为文件名 2014-04-30 14:20:57.png
        // 让不同的用户信息,保存在不同目录中
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置日期格式
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [formatter stringFromDate:[NSDate date]];
        
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mimeTpye];
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSAssert(error == nil, @"有错误");
        if (failure) {
            failure(error);
        }
    }];
}










@end
